package com.sneakxy.beetl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.FileResourceLoader;

public class ActionTemplate {

	private GroupTemplate groupTemplate;
	
	private File file;
	
	public ActionTemplate(String path) throws IOException {
		ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(path);
		Configuration cfg = Configuration.defaultConfiguration();
		this.groupTemplate = new GroupTemplate(resourceLoader, cfg);
		ClassLoader cs = ClasspathResourceLoader.class.getClassLoader();
		URL url = cs.getResource(path);
		if(url == null) {
			//兼容以前的
			url = cs.getClass().getResource(path);
		}
		this.file = new File(url.getFile());
	}
	
	public ActionTemplate(File file) throws IOException {
		FileResourceLoader resourceLoader = new FileResourceLoader(file.getAbsolutePath());
		Configuration cfg = Configuration.defaultConfiguration();
		this.groupTemplate = new GroupTemplate(resourceLoader, cfg);
		this.file = file;
	}
	
	public void write(String template, Map<String, Object> params, String out) throws BeetlException, FileNotFoundException {
		write(template, params, new FileOutputStream(new File(out)));
	}
	
	@SuppressWarnings("deprecation")
	public void write(String template, Map<String, Object> params, OutputStream os) {
		Template temp = this.groupTemplate.getTemplate(template);
		temp.binding(params);
		temp.renderTo(os);
		if(os != null) {
			IOUtils.closeQuietly(os);
		}
	}
	
	public File getFile() {
		return file;
	}

	public boolean isFile() {
		return getFile() != null;
	}
	
}
